<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>菜品</title>
    <link rel="stylesheet" href="layui/css/layui.css">
</head>
<body>
<div class="layui-container" style="padding-top: 30px;">

    <!--添加或修改菜品弹出框-开始-->
    <div id="insertOrUpdateDiv" style="display: none;padding-top: 30px;">
        <form class="layui-form" lay-filter="dataFrm" id="dataFrm">
            <input type="hidden" name="id" class="layui-input">

            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">名称：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="name" lay-verify="required|typeName" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">单价：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="price" lay-verify="required|typeName" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">口味：</label>
                    <div class="layui-input-inline">
                        <input type="text" name="flavor" lay-verify="required|typeName" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">分类：</label>
                    <div class="layui-input-inline">
                        <select name="tid" lay-verify="required" lay-search="" id="tids">

                        </select>
                    </div>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" lay-submit="" lay-filter="submit">提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
    <!--添加或修改菜谱分类弹出框-结束-->

    <fieldset class="layui-elem-field layui-field-title">
        <legend>菜品列表</legend>
    </fieldset>

    <table class="layui-hide" id="test" lay-filter="test"></table>

    <script type="text/html" id="toolbarDemo">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="insert">添加</button>
        </div>
    </script>
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" lay-event="update">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="delete">删除</a>
    </script>

    <script src="layui/layui.js" charset="utf-8"></script>
    <script>
        layui.use(['table','jquery','form'], function () {
            var table = layui.table;
            var $ = layui.jquery;
            var form = layui.form;
            var tableIns = table.render({
                elem: '#test'
                , url: '/menuApi/menuList'
                ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
                , title: '菜单列表'
                , cols: [
                    [
                        {field: 'id',  title: '编号', sort: true}
                        , {field: 'name', title: '菜品'}
                        , {field: 'price',  title: '单价'}
                        , {field: 'flavor',  title: '口味'}
                        , {
                        field: 'type',  title: '分类', templet: function (data) {
                            return data.type.name
                        }
                    }
                        , {fixed: 'right', title: '操作', toolbar: '#barDemo', align:'center', width: 115}
                    ]
                ]
                , page: true
            });

            var submitUrl;
            var submitType;
            //弹出新增菜品弹出框
            function openAddDiv(){
                addDiv=layer.open({
                    type:1,
                    title:'添加',
                    area:['370px'],
                    content:$('#insertOrUpdateDiv'),
                    success:function () {
                        //清空表单
                        $('#dataFrm')[0].reset();
                        //处理下拉框数据
                        makeSelect();
                        //添加请求url
                        submitUrl='/menuApi/insertMenu';
                        submitType='POST';
                    }
                })
            }

            var currentId=-1;
            //弹出编辑菜品弹出框
            function openUpdateDiv(data){
                addDiv=layer.open({
                    type:1,
                    title:'编辑',
                    area:['370px'],
                    content:$('#insertOrUpdateDiv'),
                    success:function () {
                        //初始化表单
                        form.val("dataFrm",data);
                        //添加请求url
                        submitUrl='/menuApi/updateMenuById';
                        submitType='PUT';
                        //将当前表单的id属性存起来
                        currentId=data.tid;
                        //处理下拉框数据
                        makeSelect();
                    }
                })

            }

            //处理下拉框数据
            function makeSelect(){
                $.get('/menuApi/typeList',function (res) {
                    var tids=$('#tids');
                    // alert(tids.html())

                    var typeInfo=res.data;
                    console.log("res："+res);

                    //遍历前先清空
                    tids.empty();
                    tids.append("<option value=''>"+'直接选择或搜索选择'+"</option>");
                    //遍历所有分类，渲染下拉框
                    $(typeInfo).each(function (index,element) {
                        // alert(element.id+"--"+element.name);

                        //如果当前分类的id==正在遍历的分类id，就给下拉增加selected属性
                        if(currentId!=-1){

                            if(currentId==element.id){
                                tids.append("<option selected='selected' value="+element.id+">"+element.name+"</option>");
                            }else{
                                tids.append("<option value="+element.id+">"+element.name+"</option>");
                            }

                        }else{
                            tids.append("<option value="+element.id+">"+element.name+"</option>");
                        }

                        console.log("下拉列表---------"+typeInfo);
                        form.render('select');
                    })
                    // alert(tids.html())

                })
            }

            //头工具栏事件
            table.on('toolbar(test)', function(obj){
                var checkStatus = table.checkStatus(obj.config.id);
                switch(obj.event){
                    case 'insert':
                        var data = checkStatus.data;
                        //弹出新增菜品弹出框
                        openAddDiv();
                        break;
                };
            });

            //监听行工具事件
            table.on('tool(test)', function (obj) {
                var data = obj.data;
                if (obj.event === 'update') {
                    //弹出编辑菜品弹出框
                    openUpdateDiv(data);
                }
                if (obj.event === 'delete') {
                    layer.confirm('真的删除【'+data.name+'】么', function(index){
                        obj.del(); //删除对应行（tr）的DOM结构
                        layer.close();
                        //向服务端发送删除指令
                        $.ajax({
                            type:'DELETE',
                            url:'/menuApi/deleteMenuById/'+data.id,
                            success:function (res) {
                                layer.msg(res.data);
                            }
                        })
                    });
                }
            });

            //提交
            form.on("submit(submit)",function (obj) {
                //序列化表单数据
                var params=$("#dataFrm").serialize();
                //请求后端添加或编辑方法
                $.ajax({
                    type:submitType,
                    url:submitUrl,
                    data:params,
                    success:function (data) {
                        if(data.data){
                            layer.msg('添加成功')
                        }else{
                            layer.alert('服务器异常', {icon: 2});
                        }

                        //关闭弹出层
                        layer.close(addDiv)
                        //刷新数据 表格
                        tableIns.reload();
                    }
                })

            })
        });
    </script>

</div>
<script>
    //二级菜单联动
    layui.use('element', function () {
        var element = layui.element;

    });
</script>
</body>
</html>